package com.atmc.filter;

import com.atmc.entity.LoginUser;
import com.atmc.utils.JwtUtil;
import com.atmc.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisUtils redisUtils;
//    @Autowired
//    @Qualifier("redisTemplate1")
//    RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1获取token  header的token
        String token = request.getHeader("token");
//        request.get
        if (!(StringUtils.hasText(token))){
            filterChain.doFilter(request,response);
            return;
        }
        //2解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
             userId = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException("token不合法！");
        }
        //3获取userId, redis获取用户信息
        LoginUser loginUser= (LoginUser) redisUtils.get("userId:" + userId);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("当前用户未登录!");
        }
        //封装Authentication
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        //5存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        //放行，让下面的过滤器执行
        filterChain.doFilter(request,response);

    }
}
